import re
import sys
import os
import subprocess
import shutil

import base
print('Step 4: Create an non-root user.')

USER_NAME_REGEX = '[a-z_][a-z0-9_-]*[$]?'

# Set name
print()
print('Please input the new user\'s name(support lower char/digits/\'-\'/\'_\')(default: archlinux):', end='')
user_name = input().lower()

if (len(user_name)) == 0:
    user_name = 'archlinux'
if not re.match(USER_NAME_REGEX, user_name):
    user_name = f'arch_{user_name}'
if not re.match(USER_NAME_REGEX, user_name):
    user_name = 'archlinux'
if len(user_name) > 32:
    user_name = user_name[:32]

print(f'Create a user named {user_name}? [Y/n]', end='')
if not base.input_yes_or_no(True):
    print('Aborting...')
    sys.exit()

# Create user
base.run(f'useradd --create-home -s /usr/bin/fish {user_name}')

# Set password
print()
print('===== Setting new user\'s passward... =====')

is_password_set = False
while not is_password_set:
    is_password_set = (base.run(f'passwd {user_name}') == 0)

# Configure sudo
print(f"""To make user {user_name} able to use sudo for all actions, please edit sudoers file like this:"
    root ALL=(ALL) ALL
    {user_name} ALL=(ALL) ALL
Edit sudoers file?[y/N]""", end='')

if base.input_yes_or_no(False):
    # base.run('EDITOR=vim visudo')
    base.run('EDITOR=nvim visudo')

# Create directories and set theirs owner
FOLDERS = (
    'Applications',
    'Builds',
    'Codes',
    'Codes-other',
    'Desktop',
    'Documents',
    'Downloads',
    'Music',
    'Pictures',
    'Videos'
)

id_strs = subprocess.run(f'id {user_name}', shell=True, stdout=subprocess.PIPE)\
    .stdout.split() # ('uid=xxxx(xxxx)', 'gid=xxxx(xxxx)')
uid = int(id_strs[0][4:-len(user_name)-2])
gid = int(id_strs[1][4:-len(user_name)-2])

for folder in FOLDERS:
    os.mkdir(f'/home/{user_name}/{folder}', 0b_111_101_101)
    os.chown(f'/home/{user_name}/{folder}', uid, gid)

shutil.copyfile('./files/AUR-PACKAGE-BUILDER.sh', f'/home/{user_name}/{FOLDERS[1]}/AUR-PACKAGE-BUILDER.sh')
os.chown(f'/home/{user_name}/{FOLDERS[1]}/AUR-PACKAGE-BUILDER.sh', uid, gid)